import { Action, createReducer, on } from "@ngrx/store"
import { addTodo, deleteTodo, todoFinish } from "../actions/todo.actions"
import { v4 as uuidv4 } from "uuid"
import { JsonPipe } from "@angular/common"

export const todoFeatureKey = "todo"
export interface Todo {
	id: string
	title: string
	completed: boolean
}

export interface State {
	todos: Todo[]
}

const todos = localStorage.getItem("todos")

export const initialState: State = {
	todos: todos ? JSON.parse(todos) : []
}

const updateLocalStorage = (todos: Todo[]) =>{
	localStorage.setItem('todos', JSON.stringify(todos))
}

export const reducer = createReducer(
	initialState,
	on(addTodo, (state, action) => {
		const todos = [
			...state.todos,
			{
				id: uuidv4(),
				title: action.title,
				completed: false
			}
		]
		updateLocalStorage(todos)
		return { ...state, todos }
	}),
	on(deleteTodo, (state, action) => {
		const newState = JSON.parse(JSON.stringify(state))
		const index = newState.todos.findIndex(
			(todo: Todo) => todo.id === action.id
		)
		newState.todos.splice(index, 1)
		updateLocalStorage(newState.todos)
		return newState
	}),
	on(todoFinish, (state, action) => {
		const newState = JSON.parse(JSON.stringify(state))
		const index = newState.todos.findIndex(
			(todo: Todo) => todo.id === action.id
		)
		newState.todos[index].completed = !newState.todos[index].completed
		updateLocalStorage(newState.todos)
		return newState
	})
)
